import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { getNewsList, deleteNews } from "@/api/news";
// import { ElMessageBox } from "element-plus";
// import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { type FormItemProps } from "../utils/types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h, toRaw } from "vue";

import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
// import { useRouter } from "vue-router";
import $router from "@/router/index";

export function useRole() {
  const form = reactive({
    type: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // const switchLoadMap = ref({});
  // const { switchStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "标题",
      prop: "title",
      minWidth: 120
    },
    {
      label: "描述",
      prop: "description",
      minWidth: 150
    },
    {
      label: "类型",
      prop: "max_num",
      minWidth: 60
    },
    {
      label: "封面图",
      // prop: "img_url",
      minWidth: 100,
      slot: "newsimg"
    },
    {
      label: "平台",
      prop: "start_time",
      minWidth: 150
    },
    {
      label: "来源",
      prop: "origin",
      minWidth: 100
    },
    {
      label: "作者",
      prop: "author",
      minWidth: 100
    },
    {
      label: "是否显示",
      prop: "userName",
      minWidth: 150
    },
    {
      label: "创建人",
      prop: "userName",
      minWidth: 150
    },
    {
      label: "更新人",
      prop: "clubName",
      minWidth: 150
    },
    // {
    //   label: "状态",
    //   minWidth: 130,
    //   cellRenderer: scope => (
    //     <el-switch
    //       size={scope.props.size === "small" ? "small" : "default"}
    //       loading={switchLoadMap.value[scope.index]?.loading}
    //       v-model={scope.row.status}
    //       active-value={1}
    //       inactive-value={0}
    //       active-text="已启用"
    //       inactive-text="已停用"
    //       inline-prompt
    //       style={switchStyle.value}
    //       onChange={() => onChange(scope as any)}
    //     />
    //   )
    // },
    {
      label: "备注",
      prop: "remark",
      minWidth: 150
    },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "add_time",
      formatter: ({ add_time }) =>
        add_time && dayjs(add_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "更新时间",
      minWidth: 180,
      prop: "update_time",
      formatter: ({ update_time }) =>
        update_time && dayjs(update_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];
  // const buttonClass = computed(() => {
  //   return [
  //     "!h-[20px]",
  //     "reset-margin",
  //     "!text-gray-500",
  //     "dark:!text-white",
  //     "dark:hover:!text-primary"
  //   ];
  // });

  // function onChange({ row, index }) {
  //   ElMessageBox.confirm(
  //     `确认要<strong>${
  //       row.status === 0 ? "停用" : "启用"
  //     }</strong><strong style='color:var(--el-color-primary)'>${
  //       row.name
  //     }</strong>吗?`,
  //     "系统提示",
  //     {
  //       confirmButtonText: "确定",
  //       cancelButtonText: "取消",
  //       type: "warning",
  //       dangerouslyUseHTMLString: true,
  //       draggable: true
  //     }
  //   )
  //     .then(() => {
  //       switchLoadMap.value[index] = Object.assign(
  //         {},
  //         switchLoadMap.value[index],
  //         {
  //           loading: true
  //         }
  //       );
  //       setTimeout(() => {
  //         switchLoadMap.value[index] = Object.assign(
  //           {},
  //           switchLoadMap.value[index],
  //           {
  //             loading: false
  //           }
  //         );
  //         message(`已${row.status === 0 ? "停用" : "启用"}${row.name}`, {
  //           type: "success"
  //         });
  //       }, 300);
  //     })
  //     .catch(() => {
  //       row.status === 0 ? (row.status = 1) : (row.status = 0);
  //     });
  // }

  async function handleDelete(row) {
    message(`您删除了标题为${row.title}的这条数据`, { type: "success" });
    const result = await deleteNews(row.id);
    console.log("result----------", result);
    if (result.error === 0) {
      onSearch();
    }
  }

  function handleSizeChange(val: number) {
    //每页几条
    console.log(`${val} items per page`);
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    toRaw(form);
    const { result } = await getNewsList({
      ...form,
      page: pagination.currentPage,
      limit: pagination.pageSize
    });
    dataList.value = result.lists;
    pagination.total = result.total;
    // pagination.pageSize = result.limit;
    // pagination.currentPage = result.page;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  //formEl
  const resetForm = () => {
    // console.log(formEl, "-----------------formEl");
    // if (!formEl) return;
    // formEl.resetFields();
    form.type = "";
    pagination.currentPage = 1;
    pagination.pageSize = 10;
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}比赛`,
      props: {
        formInline: {
          name: row?.name ?? "",
          code: row?.code ?? "",
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了比赛名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  /** 菜单权限 */
  function handleMenu() {
    message("等菜单管理页面开发后完善");
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}
  function toDetail() {
    console.log("toDetail----------");
    const parameter = { id: 1 };
    // const router = useRouter();
    const router = $router;
    // 保存信息到标签页
    useMultiTagsStoreHook().handleTags("push", {
      path: `/news/list/add`,
      name: "addNews",
      query: parameter,
      meta: {
        title: {
          zh: `新增资讯`,
          en: `addNews`
        }
        // 如果使用的是非国际化精简版title可以像下面这么写
        // title: `No.${index} - 详情信息`,
        // 最大打开标签数
        // dynamicLevel: 3
      }
    });
    console.log("router-------", router);
    // 路由跳转
    router.push({ path: "/news/list/add", query: parameter });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    // buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleMenu,
    handleDelete,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    toDetail
  };
}
